package org.scalpel.mainApps.HHObjects;


import org.scalpel.common.HHObject;


import ioio.lib.api.AnalogInput;
import ioio.lib.api.IOIO;
import ioio.lib.api.exception.ConnectionLostException;
import android.util.Log;

/**
 * @author  Jerome Monceaux, Yvanne Paviet-Salomon
 * @version 1.0
 * 
 *  * AnalogInput potentiometer = ioio.openAnalogInput(40);
 * float value = potentiometer.read();
 * ...
 * potentiometer.close();  // pin 40 can now be used for something else.
 **/

public class Jack extends HHObject {

	private static final String TAG="MyActivity";
   private boolean fIsSimulation = false;
	private int fPin = 40;
	private IOIO fIoio = null;
	
	private AnalogInput fAnalogInput = null;

    float fVoltage = 0.f;
    
    boolean fFirst = true;
    
	public Jack(String name, int pin){
		super(name);
	  fPin = pin;
	}

	protected void finalize() throws Throwable
	{
		if( fAnalogInput != null)
			fAnalogInput.close();
	  super.finalize(); //not necessary if extending Object.
	} 
	
	public void initIOIO(boolean isSimulation, IOIO ioio){
		fIsSimulation = isSimulation;

		if(fIsSimulation) return;
		
		fIoio = ioio;
		try {
			fAnalogInput = fIoio.openAnalogInput(fPin);
		} catch (ConnectionLostException e) {
			e.printStackTrace();
		};
		
	}
	
	public void updateIOIO(){

		if( fIsSimulation ) return;
		
		if( fIoio == null || 
				fAnalogInput == null
				) return;
		
		try {
			fVoltage = fAnalogInput.getVoltage();
			
			if( fVoltage < 1.f && fFirst)
			{
				fFirst = false;
				setChanged();
				notifyObservers(new Object[]{"gameStarted", null});
			}
		} catch (ConnectionLostException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		
	}
	
}
